#define CREG_BASE   0xbfd00000
#define CLOCK_CTRL0 0x220
#define CLOCK_CTRL2 0x228
#define CHIP_SAMPLE0 0x210

#define CPUPLL_LDF_OFFSET   1
#define CPUPLL_ODF_OFFSET   8

//Fout = Fin * ldf / 2^odf
//set user CPUPLL configure directly, make sure the defined value NOT exceed the min and max
//CPUPLL_LDF    //7 ~ 127
//CPUPLL_ODF    //0 ~ 7

sbc_pll_cfg:
	li	t0, CREG_BASE
	//      [12]sel, [11]pd, [10:8]odf, [7:1]ldf, [0]set
	//         25MHz            0      40*3(0x78)  0
	li	t1,  0x8f0
	sw	t1,  CLOCK_CTRL2(t0)
	li	t1,  0x8f1
	sw	t1,  CLOCK_CTRL2(t0)
	li	t2, 0x3
1:	bnez	t2, 1b
	addiu	t2, t2, -1
	li	t1,  0x0f1           // power up pll
	sw	t1,  CLOCK_CTRL2(t0)
	// wail lock
	li	t2, 0x40
1:	bnez	t2, 1b
	addiu	t2, t2, -1
	// TODO: read till lock...
	li	t1,  0x10f1		// select pll clk
	sw	t1,  CLOCK_CTRL2(t0)
	li	t1,  0x10f0		// clear set bit
	sw	t1,  CLOCK_CTRL2(t0)

cpu_pll_cfg:
	//cpu	[12]sel, [11]pd, [10:8]odf, [7:1]ldf, [0]set

//select CPU core frequency here
#if CPUFREQ>600
#define CPUPLL_LDF  CPUFREQ/50
#define CPUPLL_ODF  1
#else
#define CPUPLL_LDF  CPUFREQ/25
#define CPUPLL_ODF  2
#endif


    li  a1, (CPUPLL_LDF << CPUPLL_LDF_OFFSET) | (CPUPLL_ODF << CPUPLL_ODF_OFFSET)

	li	t0, CREG_BASE

    or  t1, a1, 0x800   //power down
	sw	t1,  CLOCK_CTRL0(t0)

    or  t1, a1, 0x801		// power down
	sw	t1,  CLOCK_CTRL0(t0)

    //wait 10 us
	li	t2, 0x100
1:	bnez	t2, 1b
	addiu	t2, t2, -1

    or  t1, a1, 0x001		// power up
	sw	t1,  CLOCK_CTRL0(t0)

	//wail lock(200 us+)
	li	t2, 0x4000
1:	bnez	t2, 1b
	addiu	t2, t2, -1

	// TODO: read till lock...
    or  t1, a1, 0x1001		// select pll clk
	sw	t1,  CLOCK_CTRL0(t0)

    or  t1, a1, 0x1000		// clear set bit
	sw	t1,  CLOCK_CTRL0(t0)
